package fr.SDroid;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import fr.SDroid.Graph.Graph;
import fr.SDroid.Graph.Ligne;
import fr.SDroid.Graph.Station;
import fr.SDroid.Onglet.Search;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class TranSpeed extends Activity {
    /** Called when the activity is first created. */
	private static Graph graph = null;
	public Station station = null;
	Element elementLigne = null;
	Ligne ligne = null;
	NodeList nodeStation = null;
	Element elementStation = null;
	NodeList nodeLien = null;
	Element elementLien = null;
	NodeList nodeCoresp = null;
	Element elementCoresp = null;
	Integer conversionInteger1 = null;
	Integer conversionInteger2 = null;
	
	
	private static String baseURL = "http://phane.d.free.fr/android/TranSpeed/";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
         setContentView(R.layout.splash);
         
         ImageView back = (ImageView)findViewById(R.id.ImageView01);
         back.setBackgroundColor(Color.parseColor("#333333"));
         
         loadSpinnerVille();
         
    }
    
    private void loadSpinnerVille() {
    	Spinner spiVille = (Spinner) findViewById(R.id.Spinner01);
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        try {
			ArrayList<String> listVille = getVille();
			if(listVille.size() == 0) { // on est pas connecter � internet
				findViewById(R.id.Button01).setEnabled(false);
				Toast.makeText(this, "veuillez vous connecter � internet", 10000).show();
			} else {
				findViewById(R.id.Button01).setEnabled(true);
			}
			for(int i = 0; i < listVille.size(); i++) {
				adapter.add(listVille.get(i));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        spiVille.setAdapter(adapter);
        
        findViewById(R.id.Button01).setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				String ville = ((Spinner) findViewById(R.id.Spinner01)).getSelectedItem().toString();
				loadGraph(ville);
			}
		});
    }
    
    private void loadGraph(final String ville) {
    	final ProgressDialog pd = ProgressDialog.show(this, "Working...", "Création du plan de "+ville, true, false);    	
    	new Thread(new Runnable() {
			
			public void run() {
				FileInputStream fIn = null; 
		        
		        File f = new File(getFilesDir()+File.separator+ville+"-Plan.xml");
//		        if(f.exists())
//		        	f.delete();
		        if(!f.exists()) {
		        	try {
		        		
						URL urlMap = new URL(baseURL+"ville/"+ville+"/"+ville+"-Plan.xml");
					
						HttpURLConnection connection = (HttpURLConnection) urlMap.openConnection();
						InputStream inputStream = connection.getInputStream();
						InputStreamReader reader = new InputStreamReader(inputStream);
						BufferedReader in = new BufferedReader(reader);
						
						FileOutputStream fOut = openFileOutput(ville+"-Plan.xml", MODE_PRIVATE);
					    OutputStreamWriter osw = new OutputStreamWriter(fOut); 
					    while (in.ready()) {
					    	osw.write(in.readLine());
					    }
					    osw.flush();
					    fOut.close();
					    
					    // On traite les images
					    getImage(ville);
					   

		        	} catch (MalformedURLException e) {
		        		handler.sendEmptyMessage(1);
						e.printStackTrace();
					} catch (IOException e1) {
						handler.sendEmptyMessage(1);
						e1.printStackTrace();
					}
		        } 
		        
		        if(f.exists()) {
			        try {
			        	fIn = openFileInput(ville+"-Plan.xml");
			        	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			        	DocumentBuilder db = dbf.newDocumentBuilder();
			        	Document doc = db.parse(fIn);
			        	
			        	graph = parseDocument(doc);
			        				        	
			        	handler.sendEmptyMessage(0);
			        	
			        } catch (Exception e) {
					}
			     }
		        
				
				
				pd.dismiss();
			}
		}).start();
    	
    }
    
    private Handler handler = new Handler() {
    	public void handleMessage(android.os.Message msg) {
    		if(msg.what == 0) {
    			startOnglet(graph);
    		}
    		else {
    			displayMessage(msg.what);
    		}
    		
    	}
    };
    
    private void displayMessage(Integer message) {
    	if(message == 1) {
			Toast.makeText(this, "Impossible de telecharger le fichier", 10000).show();
		}
    	if(message == 2) {
			Toast.makeText(this, "Impossible d'ouvrir le fichier", 10000).show();
		}
    	Toast.makeText(this, message.toString(), 10000).show();
    }
    
    private void startOnglet(Graph g) {
    	Intent ongletIntent = new Intent(this, Search.class);
    	this.startActivity(ongletIntent);
    }
    
    private Graph parseDocument(Document doc) {
    	graph = new Graph();
  
    	Element root = doc.getDocumentElement();
    	graph.setVille(root.getAttribute("ville"));
    	graph.setVersion(Double.parseDouble(root.getAttribute("version")));
    	
    	NodeList nodeLigne = root.getElementsByTagName("ligne");
    	
   	 	for (int i = 0; i < nodeLigne.getLength(); i++) {
   	 		elementLigne = (Element)nodeLigne.item(i);
   	 		ligne = new Ligne(elementLigne.getAttribute("name"));
   	 		//on charge l'image de la  ligne
   	 		String lig = getFilesDir()+File.separator+graph.getVille()+"-"+ligne.getName().replace(" ", "")+".png";
//   	 		Bitmap image = BitmapFactory.decodeFile(lig);
   	 		ligne.setImage(new BitmapDrawable(lig));
   	 		graph.addLigne(ligne);
   	 		nodeStation = elementLigne.getElementsByTagName("station");
   	 		for (int j = 0; j < nodeStation.getLength(); j++) {
   	 			elementStation = (Element) nodeStation.item(j);
   	 			station = new Station(ligne,
   	 					Integer.parseInt(elementStation.getAttribute("id")),
   	 					elementStation.getAttribute("name"),
   	 					elementStation.getAttribute("latitude"),
   	 					elementStation.getAttribute("longitude"));
   	 			ligne.addStation(station);
   	 		}
   	 		nodeLien = elementLigne.getElementsByTagName("lien");
   	 		for(int li = 0; li < nodeLien.getLength(); li++) {
   	 			elementLien = (Element) nodeLien.item(li);
   	 			ligne.createUniqueLien(Integer.parseInt(elementLien.getAttribute("station1")),Integer.parseInt(elementLien.getAttribute("station2")));
   	 		}
   	 	}
   	 	
   	 	nodeCoresp = root.getElementsByTagName("coresp");
   	 	for(int i = 0; i < nodeCoresp.getLength(); i++) {
   	 		elementCoresp = (Element)nodeCoresp.item(i);
   	 		graph.createCoresp(Integer.parseInt(elementCoresp.getAttribute("station1")), Integer.parseInt(elementCoresp.getAttribute("station2")));
   	 	}
    	
    	return graph;
    	
    }
    
    public static Graph getGraph() {
    	return graph;
    }
    
    public void getImage(String ville) throws IOException {
    	ArrayList<String> tableau = new ArrayList<String>();
    	URL listImage = new URL(baseURL+"ville/"+ville+"/");
		HttpURLConnection conn = (HttpURLConnection) listImage.openConnection();
		conn.setRequestMethod("GET");
		conn.connect();
		    
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream in2 = conn.getInputStream();
            InputStreamReader reader2 = new InputStreamReader(in2);
            BufferedReader buffer = new BufferedReader(reader2);
             
            while (buffer.ready()) {
            	String temp = buffer.readLine();
             	if(temp.contains("png") && temp.contains("ALT=\"[IMG]\"")) {
             		String fileTemp = temp.substring(temp.indexOf("<A HREF="), temp.indexOf(">"));
             		String img = fileTemp.substring(9, fileTemp.length()-1);
             		getAndWriteImage(img, baseURL+"ville/"+ville+"/"+img);
             	}
             }
		 }
    }
    
    public ArrayList<String> getVille() throws IOException {
    	ArrayList<String> tableau = new ArrayList<String>();
    	ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    	if((connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED) || (connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)) {
    		FileOutputStream fileOut = openFileOutput("liste_ville.txt", MODE_PRIVATE);
    		OutputStreamWriter writer = new OutputStreamWriter(fileOut);
    		URL listVille = new URL(baseURL+"ville/");
        	HttpURLConnection conn = (HttpURLConnection) listVille.openConnection();
        	if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    			InputStream in2 = conn.getInputStream();
                InputStreamReader reader2 = new InputStreamReader(in2);
                BufferedReader buffer = new BufferedReader(reader2);
                
                while(buffer.ready()) {
                	String temp = buffer.readLine();
                	if(temp.contains("[DIR]")) {
                		String villeTemp = temp.substring(temp.indexOf("<A HREF="), temp.indexOf(">"));
                		String ville = villeTemp.substring(9,villeTemp.length() - 2);
                		tableau.add(ville);
                		writer.write(ville+"\n");
                	}
                }
        	}
        	writer.flush();
        	writer.close();
        	
    	} else {
    		// on essai d'ouvrir le fichier
    		try {
    		FileInputStream fIn = openFileInput("liste_ville.txt");
    		InputStreamReader reader = new InputStreamReader(fIn);
    		BufferedReader buffer = new BufferedReader(reader);
    		 while(buffer.ready()) {
             	String temp = buffer.readLine();
             	tableau.add(temp);
             }
    		} catch (FileNotFoundException e) {
				// TODO: handle exception
			}
    		
    	}
    	return tableau;
    }
    
    public void getAndWriteImage(String name, String path) {
        BitmapFactory.Options bmOptions;
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;
        InputStream in = null;
        Bitmap bm = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                in = conn.getInputStream();
                bm = BitmapFactory.decodeStream(in, null, bmOptions);
                in.close();
   //             File f = new File(File.separator + "sdcard" + File.separator + "TranSpeed" + File.separator+name);
   //             FileOutputStream fOut = new FileOutputStream(f, false);
                FileOutputStream fOut = openFileOutput(name, MODE_PRIVATE);
                bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                fOut.close();
            }
            
        } catch (IOException e1) {    e1.printStackTrace();   }
    }
}